package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Team;
import service.TeamService;
import service.UserService;
import service.impl.TeamServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author CY
 * @date 2022/12/17 16:02
 **/
@WebServlet("/teamAdd")
public class TeamAddServlet extends HttpServlet {
    TeamService teamService = new TeamServiceImpl();
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        //Json解析
        final BufferedReader bufferedReader = new BufferedReader(req.getReader());
        String line = null;
        final StringBuilder json = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            json.append(line);
        }
        final JSONObject jsonObject = JSON.parseObject(json.toString());
        //构造结果
        JSONObject message = new JSONObject();

        final Team team = new Team();
        team.setTname(jsonObject.getString("tname"));
        team.setLid(jsonObject.getInteger("lid"));
        team.setRid(jsonObject.getLong("rid"));
        team.setTurl(jsonObject.getString("turl"));
        //获取老师名字
        String teacherName = jsonObject.getString("teacherName");
        //根据老师名字获取smid
        int smid = userService.findIdByName(teacherName);
        if (smid == 0) {
            message.put("statue", "0");
            message.put("Msg", "无此老师");
            resp.getWriter().write(message.toString());
        } else {
            //存储获取的smid
            team.setSmid(smid);
            team.setPass(jsonObject.getLong("pass"));

            //判断是否已经组队
            boolean isHaveTeam = teamService.teamByIdAndRace(jsonObject.getInteger("lid"), jsonObject.getInteger("rid"));
            if (isHaveTeam) {
                message.put("statue", "0");
                message.put("Msg", "已经组队");
                resp.getWriter().write(message.toString());
            } else {

                //返回新增队伍的自然主键
                int teamAdd = teamService.teamAdd(team);

                if (teamAdd != 0 && teamService.teamUserAdd((int) team.getLid(), teamAdd) == 1) {
                    message.put("statue", "1");
                    message.put("Msg", "添加成功");
                } else {
                    message.put("statue", "0");
                    message.put("Msg", "添加失败");
                }
                resp.getWriter().write(message.toString());
            }
        }
    }
}